package com.tju.Util;


import com.tju.model.MenuObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Boyu on 2017/2/27.
 */
public class MenuTree {
    private StringBuffer html = new StringBuffer();
    private List<MenuObject> nodes;

    public MenuTree(List<MenuObject> nodes){
        this.nodes = nodes;
    }

    public String buildTree(){
        for (MenuObject node : nodes) {

            int index = 0;
            if (node.getParent() == 0) {
                if(!getChildren(node).isEmpty()) {

                    if (index == 0) {
                        html.append("<li class=\"active\">");
                    } else {
                        html.append("<li>");
                    }
                    index++;
                    html.append("<a href=\"#\">\n" +
                            "<i class=\"fa fa-home\"></i>\n" +
                            " <span class=\"nav-label\">" + node.getMemo() + "</span>\n" +
                            " <span class=\"fa arrow\"></span>\n" +
                            "</a>");
                    html.append("<ul class=\"nav nav-second-level\">");
                    build(node);
                    html.append("</ul>");
                    html.append("</li>");
                }
            }
        }
        return html.toString();
    }

    private void build(MenuObject node){
        List<MenuObject> children = getChildren(node);
        for (MenuObject child : children) {
            List<MenuObject> thirdLevel = getChildren(child);
            if(!thirdLevel.isEmpty()) {
                html.append("<li>\n" +
                        "<a href=\"#\">" + child.getMemo() + "<span class=\"fa arrow\"></span></a>\n" +
                        "<ul class=\"nav nav-third-level\">");
                build(child);
                html.append("\r\n</ul>");
            }else{
                html.append("<li>\n" +
                        "<a class=\"J_menuItem\" href=\""+child.getUrl()+"\" data-index=\"0\">\n" +
                        child.getMemo()+"</a>\n" +
                        " </li>");
            }
        }
    }

    private List<MenuObject> getChildren(MenuObject node){
        List<MenuObject> children = new ArrayList<MenuObject>();
        Integer id = node.getId();
        for (MenuObject child : nodes) {
            if (id.equals(child.getParent())) {
                children.add(child);
            }
        }
        return children;
    }
}
